/**
 * @created by jiangcheng 2017-11-15
 * @updated by weimei1 2018-09-18 重构为vue
 * @description 登录页
 */
define([
  './themes/lang/' + window.YUFP_SYS_CONFIG.language + '/pages/common/login/login.js',
  './themes/lang/' + window.YUFP_SYS_CONFIG.language + '/common/logicSystem.js',
  './libs/jsencrypt/jsencrypt.min.js'], function (require, exports) {
  /* eslint camelcase: 1  */
  // 生成唯一识别号
  function genUUID(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [],
      i;
    radix = radix || chars.length;

    if (len) {
      for (i = 0; i < len; i++) {
        uuid[i] = chars[0 | Math.random() * radix];
      }
    } else {
      var r;

      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';

      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
        }
      }
    }

    return uuid.join('');
  }

  var clientId =  genUUID(16, 16) + Date.parse(new Date());
  /**
   * 页面加载完成时触发
   * @param hashCode 路由ID
   * @param data 传递数据对象
   * @param cite 页面站点信息
   */
  exports.ready = function (hashCode, data, cite) {
    yufp.custom.vue({
      el: cite.el,
      data: function () {
        var _this = this;
        return {
          language: window.YUFP_SYS_CONFIG.language,
          isShowImage : YUFP_SYS_CONFIG.showImageCode,
          dialogVisible: false,
          localToken: null,
          logicSysList: null,
          msgShow: false,
          sysListShow: false,
          message: null,
          borderColor: null,
          sysLogicId: null, // 逻辑系统ID
          sysLogicName: null, // 逻辑系统名称
          username: '', // 用户名
          password: '', // 密码
          imageCode: null, // 验证码
          imageCodePictureUrl: yufp.service.getUrl({
            url: backend.uaaService + '/api/codeImage/' + clientId // + '?t=' + (new Date()).getTime()
          }),
          passwdFields: [{
            columnCount: 1,
            fields: [{
              field: 'oldPassWord',
              label: this.$t('login.ymm'),
              type: 'password',
              placeholder: this.$t('login.ymm'),
              rules: [{
                required: true,
                message: this.$t('login.qsrymm'),
                trigger: 'blur'
              }]
            },
            {
              field: 'newPassWord',
              label: this.$t('login.mm'),
              type: 'password',
              placeholder: this.$t('login.mm'),
              rules: [{
                required: true,
                message: this.$t('login.qsrmm'),
                trigger: 'blur'
              },
              {
                max: 40,
                message: this.$t('login.cdbcggzf'),
                trigger: 'blur'
              }
              ]
            },
            {
              field: 'confirmPassWord',
              label: this.$t('login.qrmm'),
              type: 'password',
              placeholder: this.$t('login.qrmm'),
              rules: [{
                required: true,
                message: this.$t('login.qsrqrmm'),
                trigger: 'blur'
              },
              {
                max: 40,
                message: this.$t('login.cdbcggzf'),
                trigger: 'blur'
              }
              ]
            }
            ]
          }],
          buttons: [{
            label: this.$t('login.zz'),
            type: 'primary',
            icon: 'yx-loop2',
            op: 'reset',
            click: function (model) { }
          },
          {
            label: this.$t('login.bc'),
            type: 'primary',
            icon: 'check',
            op: 'submit',
            click: function (model, valid) {
              if (valid) {
                _this.saveFn();
              }
            }
          }
          ]
        };
      },
      methods: {
        // 鼠标划入展示逻辑系统列表
        mouseoverFn: function () {
          this.sysListShow = true;
        },
        // 鼠标点击，逻辑系统列表取消展示
        clickFn: function () {
          this.sysListShow = false;
        },
        // 逻辑系统选择
        sysChooseFn: function (item) {
          this.sysLogicId = item.key;
          this.sysLogicName = item.value;
        },
        // 登录提交
        submitFn: function () {
          if (this.sysLogicId == null || !this.sysLogicId || this.sysLogicId == '') {
            this.message = this.$t('login.ljxtjzycqlxxtgly');
            this.msgShow = true;
            return;
          }
          this.checkImageFn();
        },
        // 校验图形验证码
        /**
         * 有两种方式进行处理
         * 1、输入验证码后立即请求后台进行校验；
         * 2、输入验证码，点击登录时，先发请求校验验证码，验证通过之后再进行登录处理
         */
        checkImageFn: function () {
          if (this.username == '') {
            this.message = this.$t('login.qsryhm');
            this.msgShow = true;
            this.$refs.username.focus();
            return;
          }


          if (this.password == '') {
            this.message = this.$t('login.qsrmm');
            this.msgShow = true;
            this.$refs.password.focus();
            return;
          }
          if(window.YUFP_SYS_CONFIG.showImageCode)
           if (this.imageCode == '') {
             this.message = '请输入验证码!';
             this.msgShow = true;
             this.$refs.imageCode.focus();
             return;
           }
          this.msgShow = false;
          this.loginFn();
        },
        // 刷新图形验证码
        freshImageCodeFn: function () {
          // this.$refs.validateImg.src = yufp.service.getUrl({
          //   url: backend.uaaService + '/api/codeImage/' + clientId // + '?t=' + (new Date()).getTime()
          // });;
          this.imageCode = '';
        },
        // 查询逻辑系统列表
        querylogicSysFn: function () {
          var _this = this;
          yufp.service.request({
            needToken: false,
            url: backend.appOcaService + 'api/adminsmlogicsys/logicsyskv',
            method: 'get',
            callback: function (code, message, response) {
              var logicSysList = response.data;
              if (typeof logicSysList !== 'undefined' && logicSysList !== null) {
                for (var i = 0; i < logicSysList.length; i++) {
                  var temp = yufp.language.getLocaleText('logicSystem.' + logicSysList[i]['i18nKey']);
                  if (temp) {
                    logicSysList[i].value = temp;
                  }
                }
                _this.logicSysList = logicSysList;
                _this.sysLogicName = logicSysList[0].value;
                _this.sysLogicId = logicSysList[0].key;
              }
            }
          });
        },
        // 登录
        loginFn: function () {
          var headers1 = {
            'Content-Type': 'application/json; charset=UTF-8',
            'Authorization': 'Basic d2ViX2FwcDo='
          };
          var data1 = {
            clientId: clientId,
            imageCode: this.imageCode
          };

          var headers2 = {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Authorization': 'Basic d2ViX2FwcDo='
          };
          var password = this.password;
          var encodePwd = this.encodePassword(password);

          var data2 = {
            username: this.username,
            password: encodePwd,
            grant_type: 'password',
            passwordType: '2',
            sysId: this.sysLogicId
          };

          var  imageCodeUrl = backend.uaaService + '/api/codeImage/verifyCodeImage';
          var _this = this;
          if(window.YUFP_SYS_CONFIG.showImageCode) {
            yufp.service.request({
              needToken: false,
              url: imageCodeUrl,
              method: 'post',
              headers: headers1,
              data: data1,
              callback: function (code, message, response) {
                if (!response || !code == '0') {
                  var msg = response && response.message ? response.message : _this.$t('login.yzmcw');

                  _this.message = msg;
                  _this.msgShow = true;

                  _this.imageCode = '';

                  // 生成新的图形验证码
                  _this.freshImageCodeFn();
                  return false;
                } else {

                  yufp.service.request({
                    needToken: false,
                    url: backend.uaaService + '/oauth/token',
                    method: 'post',
                    headers: headers2,
                    data: data2,
                    callback: function (code, message, response) {
                      if (response && response.access_token && !response.code) {
                        yufp.service.putToken({
                          access_token: response.access_token,
                          refresh_token: response.refresh_token,
                          expires_in: response.expires_in
                        });
                        yufp.session.loadUserSession(function () {
                          if (yufp.settings.auditLog) {
                            yufp.util.loginInfoLog('login');
                          }
                          yufp.router.to('frame');
                        });
                      } else if (response && response.code == '10000002') {
                        var strategyMessage = response.strategyMessage;
                        if (strategyMessage) {
                          var i = 0;
                          var warn = setInterval(function () {
                            _this.$notify({
                              message: strategyMessage[i].message,
                              type: response.level
                            });
                            if (i < strategyMessage.length - 1) {
                              i++;
                            } else {
                              clearInterval(warn);
                            }
                          }, 10);
                        }
                        if (response.creStrategyName == 'LOGIN_FIRST_RULE') {
                          _this.localToken = response;
                          _this.dialogVisible = true;
                        } else {
                          yufp.service.putToken({
                            access_token: response.access_token,
                            refresh_token: response.refresh_token,
                            expires_in: response.expires_in
                          });
                          yufp.session.loadUserSession(function () {
                            if (yufp.settings.auditLog) {
                              yufp.util.loginInfoLog('login');
                            }
                            yufp.router.to('frame');
                          });
                        }
                      } else if (response && response.code == '10000001') {
                        if (response.message == 'Bad credentials' || response.message == '坏的凭证') {
                          _this.message = _this.$t('login.yzhummcw');
                          _this.freshImageCodeFn();
                          _this.msgShow = true;
                        } else {
                          _this.message = response.message;
                          _this.freshImageCodeFn();
                          _this.msgShow = true;
                        }
                      } else {
                        var msg = response && response.message ? response.message : '登录失败，请联系系统管理员！';
                        _this.message = msg;
                        _this.freshImageCodeFn();
                        _this.msgShow = true;
                      }
                    }
                  });
                }
              }
            });
          }else{
            yufp.service.request({
              needToken: false,
              url: backend.uaaService + '/oauth/token',
              method: 'post',
              headers: headers2,
              data: data2,
              callback: function (code, message, response) {
                if (response && response.access_token && !response.code) {
                  yufp.service.putToken({
                    access_token: response.access_token,
                    refresh_token: response.refresh_token,
                    expires_in: response.expires_in
                  });
                  yufp.session.loadUserSession(function () {
                    if (yufp.settings.auditLog) {
                      yufp.util.loginInfoLog('login');
                    }
                    yufp.router.to('frame');
                  });
                } else if (response && response.code == '10000002') {
                  var strategyMessage = response.strategyMessage;
                  if (strategyMessage) {
                    var i = 0;
                    var warn = setInterval(function () {
                      _this.$notify({
                        message: strategyMessage[i].message,
                        type: response.level
                      });
                      if (i < strategyMessage.length - 1) {
                        i++;
                      } else {
                        clearInterval(warn);
                      }
                    }, 10);
                  }
                  if (response.creStrategyName == 'LOGIN_FIRST_RULE') {
                    _this.localToken = response;
                    _this.dialogVisible = true;
                  } else {
                    yufp.service.putToken({
                      access_token: response.access_token,
                      refresh_token: response.refresh_token,
                      expires_in: response.expires_in
                    });
                    yufp.session.loadUserSession(function () {
                      if (yufp.settings.auditLog) {
                        yufp.util.loginInfoLog('login');
                      }
                      yufp.router.to('frame');
                    });
                  }
                } else if (response && response.code == '10000001') {
                  if (response.message == 'Bad credentials' || response.message == '坏的凭证') {
                    _this.message = _this.$t('login.yzhummcw');
                    _this.freshImageCodeFn();
                    _this.msgShow = true;
                  } else {
                    _this.message = response.message;
                    _this.freshImageCodeFn();
                    _this.msgShow = true;
                  }
                } else {
                  var msg = response && response.message ? response.message : '登录失败，请联系系统管理员！';
                  _this.message = msg;
                  _this.freshImageCodeFn();
                  _this.msgShow = true;
                }
              }
            });
          }
        },
        // 登录密码加密
        encodePassword: function (pwd) {
          var encrypt = new window.JSEncrypt();
          encrypt.setPublicKey(yufp.util.getRSAPublicKey());
          var encryptPwd = encrypt.encrypt(pwd);
          var encodePwd = encodeURIComponent(encryptPwd);
          return encodePwd;
        },
        // 匹配密码加密
        matchPassword: function (pwd) {
          var encrypt = new window.JSEncrypt();
          encrypt.setPublicKey(yufp.util.getRSAPublicKey());
          var encryptPwd = encrypt.encrypt(pwd);
          return encryptPwd;
        },
        // 用户首次登录修改密码-保存方法
        saveFn: function () {
          var _this = this;
          var fields = _this.$refs.passwdform.formModel;
          var newPassWord = fields.newPassWord;
          var confirmPassWord = fields.confirmPassWord;
          if (newPassWord != confirmPassWord) {
            _this.$message({
              message: _this.$t('login.qrmmymmbyz'),
              type: 'error'
            });
            return;
          }
          this.getUserId(fields);
        },
        getUserId: function (fields) {
          var _this = this;
          yufp.service.putToken({
            access_token: _this.localToken.access_token,
            refresh_token: _this.localToken.refresh_token,
            expires_in: _this.localToken.expires_in
          });
          var loginCode = _this.username;
          yufp.service.request({
            url: backend.appOcaService + '/api/adminsmuser/getUserId?loginCode=' + loginCode,
            method: 'POST',
            callback: function (code, message, response) {
              if (code === 0 && response.code == 0) {
                if (response.data) {
                  var userId = response.data;
                  _this.eqaul2UsingPassword(fields, userId); // 校验填写的原密码是否正确
                } else {
                  _this.$message({
                    message: _this.$t('login.mmbcsb'),
                    type: 'warning'
                  });
                  yufp.service.removeToken();
                }
              }
              return;
            }
          });
        },
        eqaul2UsingPassword: function (fields, userId) {
          var _this = this;
          var oldPassWord = fields.oldPassWord;
          var encodeOldPwd = _this.matchPassword(oldPassWord);
          var newPassWord = fields.newPassWord;
          if (newPassWord == oldPassWord) {
            _this.$message({
              message: _this.$t('login.xmmbnhjmmxt'),
              type: 'warning'
            });
            return;
          }

             var newPassWord = fields.newPassWord;
            var encodePwd = _this.matchPassword(newPassWord);

          yufp.service.request({
            url: backend.uaaService + '/api/use/user/password/setPwd',
            method: 'POST',
            data: {
              sysId: _this.sysLogicId,
              pwd: encodeOldPwd,
              passwordType: '2',
              userId: userId,
              password: encodePwd
            },
            callback: function (code, message, response) {
              if (code == 0 && response.code == 0) {
                  _this.$message({
                      message: _this.$t('login.mmxgcgqsyxmmdl')
                            }, 'success');
                            _this.dialogVisible = false;
                            _this.password = null;
                            _this.imageCode = null;
                            _this.freshImageCodeFn();
                            yufp.service.removeToken();
                          } else {
                            _this.$message({
                              message: _this.$t('login.mmxgsb'),
                              type: 'warning'
                            });
                            yufp.service.removeToken();
                          }
            }
          });
        },
        pwdStrategyCheck: function (fields, userId) {
          var _this = this;
          var newPassWord = fields.newPassWord;
          var encodePwd = _this.matchPassword(newPassWord);
          yufp.service.request({
            url: backend.uaaService + '/api/passwordcheck/checkpwd',
            method: 'POST',
            data: {
              sysId: _this.sysLogicId,
              pwd: encodePwd,
              userId: userId,
              passwordType: '2'
            },
            callback: function (code, message, response) {
              if (code == 0 && response.code == '10100001') {
                _this.resetPwd(encodePwd, userId); // 新密码通过校验策略，重置登录密码
              } else {
                _this.$message({
                  message: response.message,
                  type: 'warning'
                });
                yufp.service.removeToken();
              }
            }
          });
        },
        resetPwd: function (encodePwd, userId) {
          var _this = this;
          yufp.service.request({
            url: backend.appOcaService + '/api/adminsmuser/resetpwd',
            method: 'POST',
            data: JSON.stringify({
              userId: userId,
              password: encodePwd,
              updateUser: userId
            }),
            callback: function (code, message, response) {
              if (code == 0 && response.code == 0) {
                _this.$message({
                  message: _this.$t('login.mmxgcgqsyxmmdl')
                }, 'success');
                _this.dialogVisible = false;
                _this.password = null;
                _this.imageCode = null;
                _this.freshImageCodeFn();
                yufp.service.removeToken();
              } else {
                _this.$message({
                  message: _this.$t('login.mmxgsb'),
                  type: 'warning'
                });
                yufp.service.removeToken();
              }
            }
          });
        }
      },
      mounted: function () {
        this.querylogicSysFn();
        this.freshImageCodeFn();
      }
    });
  };
});